#region License

// This file is part of Grawlix.
// 
// Grawlix is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// Grawlix is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public
// License along with Grawlix.  If not, see
// <http://www.gnu.org/licenses/>.

#endregion

using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace Grawlix.Services.Resources
{
	/// <summary>
	/// A resource with identity-preserving marshal-by-value
	/// semantics.
	/// </summary>
	/// <typeparam name="TDeclare">The type of resource that this
	/// class declares it proxies.</typeparam>
	/// <typeparam name="TDefine">The actual type of resource
	/// proxied.</typeparam>
	[Serializable]
	[SuppressMessage("Microsoft.Usage", "CA2240",
		Justification =
			"Not applicable because it is serialized by proxy.")]
	public abstract class AbstractResourceProxy<TDeclare,
	                                            TDefine> :
	                                            	IDynamicResource,
	                                            	ISerializable
		where TDeclare : IDynamicResource
		where TDefine : AbstractResourceProxy<TDeclare, TDefine>,
			TDeclare
	{
		/// <summary>
		/// The identifier the resource was created with.
		/// </summary>
		private readonly Uri _identifier;

		/// <summary>
		/// Flag indicating resource load failure.
		/// </summary>
		private bool _loadFailed;

		/// <summary>
		/// The attached cache.
		/// </summary>
		private ResourceCache<TDeclare, TDefine> _resourceCache;

		/// <summary>
		/// The internal object state.
		/// </summary>
		private object _state;

		/// <summary>
		/// Initializes the 
		/// <see cref="AbstractResourceProxy{TDeclare,TDefine}"/> with
		/// a given URI.
		/// </summary>
		/// <param name="identifier">The unique identifier for this
		/// instance.</param>
		protected AbstractResourceProxy(Uri identifier)
		{
			_identifier = identifier;
		}

		/// <summary>
		/// Gets the identifier.
		/// </summary>
		/// <value>The identifier.</value>
		public Uri Identifier
		{
			get { return _identifier; }
		}

		/// <summary>
		/// Gets a value indicating whether [load failed].
		/// </summary>
		/// <value><c>true</c> if [load failed]; otherwise, <c>false</c>.</value>
		public bool LoadFailed
		{
			get { return _loadFailed; }
		}

		/// <summary>
		/// Gets a value indicating whether this 
		/// <see cref="AbstractResourceProxy{TDeclare,TDefine}"/> is ready.
		/// </summary>
		/// <value><c>true</c> if ready; otherwise, <c>false</c>.
		/// </value>
		public bool Ready
		{
			get { return _state != null; }
		}

		/// <summary>
		/// Accesses the internal state object.
		/// </summary>
		/// <returns>The internal state object.</returns>
		/// <exception cref="System.InvalidOperationException">The resource is
		/// not ready.</exception>
		protected object UntypedState
		{
			get
			{
				EnsureReady();
				return _state;
			}
		}

		/// <summary>
		/// Attaches to the specified resource cache.
		/// </summary>
		/// <param name="resourceCache">The resource cache to attach
		/// to.</param>
		internal void Attach(
			ResourceCache<TDeclare, TDefine> resourceCache)
		{
			_resourceCache = resourceCache;
		}

		/// <summary>
		/// Convenience function that raises an 
		/// <see cref="InvalidOperationException"/> if the resource is
		/// not ready.
		/// </summary>
		/// <exception cref="InvalidOperationException">The resource is
		/// not ready.</exception>
		protected void EnsureReady()
		{
			if (!Ready)
			{
				throw new InvalidOperationException(
					"Unable to access a resource (" + this + ") because " +
					"it is not yet ready. " +
					"Be sure to check the Ready parameter before " +
					"accessing most resource operations.");
			}
		}

		/// <summary>
		/// Releases unmanaged resources and performs other cleanup
		/// operations before the
		/// <see cref="AbstractResourceProxy{TDeclare,TDefine}"/> is
		/// reclaimed by garbage collection.
		/// </summary>
		~AbstractResourceProxy()
		{
			if (_resourceCache != null)
				_resourceCache.RemoveResource(this);
		}

		/// <summary>
		/// Populates a 
		/// <see cref="T:System.Runtime.Serialization.SerializationInfo"/>
		/// with the data needed to serialize the target object.
		/// </summary>
		/// <param name="info">The 
		/// <see cref="T:System.Runtime.Serialization.SerializationInfo"/>
		/// to populate with data.</param>
		/// <param name="context">The destination (see 
		/// <see cref="T:System.Runtime.Serialization.StreamingContext"/>
		/// ) for this serialization.</param>
		/// <exception cref="T:System.Security.SecurityException">
		/// The caller does not have the required permission.
		/// </exception>
		/// <exception cref="SerializationException">Attempt to
		/// serialize a detached resource proxy.</exception>
		[SecurityPermission(SecurityAction.LinkDemand,
			Flags = SecurityPermissionFlag.SerializationFormatter)]
		[SuppressMessage("Microsoft.Design", "CA1033",
			Justification =
				"Not applicable because it is serialized by proxy.")]
		void ISerializable.GetObjectData(SerializationInfo info,
		                                 StreamingContext context)
		{
			if (_resourceCache == null)
			{
				throw new SerializationException(
					"Attempt to serialize a detached resource proxy.");
			}
			info.AddValue("Identifier", Identifier, typeof(Uri));
			IGameKernel kernel =
				GameKernelStreamingContext.TryGetContextKernel(context);
			if (kernel == null)
			{
				info.AddValue("Repository", _resourceCache.Repository,
				              typeof(
				              	ResourceRepository<TDeclare, TDefine>));
				info.SetType(
					typeof(LocalResourceObjectReference<TDeclare, TDefine>));
			}
			else
			{
				info.SetType(
					typeof(PersistentResourceObjectReference<TDeclare>));
			}
		}

		/// <summary>
		/// Sets the state of this resource.
		/// </summary>
		/// <param name="resourceState">The state information.</param>
		internal void SetState(ResourceState resourceState)
		{
			_state = resourceState.StateData;
			_loadFailed = resourceState.LoadFailed;
		}

		/// <summary>
		/// Returns a <see cref="T:System.String"/> that represents the
		/// current <see cref="T:System.Object"/>.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.String"/> that represents the current
		/// <see cref="T:System.Object"/>.
		/// </returns>
		public override string ToString()
		{
			return typeof(TDefine).Name + "-" + _identifier;
		}
	}
}